package impl

import (
	"context"
	"github.com/starmotioncf/common/log"
	"github.com/starmotioncf/common/restriction"
	"github.com/starmotioncf/soutchatinternal"
	"github.com/starmotioncf/soutchatinternal/constant"
	"github.com/starmotioncf/soutchatinternal/repository"
	"github.com/starmotioncf/soutchatinternal/service"
	"github.com/starmotioncf/soutchatpkg/jwt"
	"github.com/starmotioncf/soutchatpkg/utils"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"golang.org/x/exp/slices"
)

type restrictionService struct {
	*service.Service
	restrictionRepo repository.RestrictionRepository
}

func NewRestrictionService(s *service.Service, restrictionRepo repository.RestrictionRepository) service.RestrictionService {
	return &restrictionService{
		Service:         s,
		restrictionRepo: restrictionRepo,
	}
}

// MaskChinaUser 检查并封禁国内用户
func (s *restrictionService) MaskChinaUser(ctx *gin.Context) bool {
	//非国内用户直接跳过
	if !s.checkChinaUser(ctx) {
		return false
	}
	// header := context2.NewApiHeader(req)
	// ip := header.GetIp()
	// mac := header.GetMac()
	// uid := uint64(header.GetUid())
	// //检查是否在白名单
	// if s.CheckOneInWhite(ctx, uid, ip, mac) {
	// 	s.debugLog(fmt.Sprintf("[MaskChinaUser] 白名单用户：%d-%s-%s", uid, ip, mac))
	// 	return false
	// }
	// //为0不封禁，大于0按位计算封禁对象
	// forbidChinaUser := s.settingRepo.GetInt("forbid_china_user")
	// if forbidChinaUser == 0 {
	// 	s.debugLog(fmt.Sprintf("[MaskChinaUser] 检测到大陆用户：%d-%s-%s", uid, ip, mac))
	// 	return false
	// }
	// //大于等于这个财富等级的不封禁
	// maskForbidChinaUserWealthLv := s.settingRepo.GetInt("forbid_china_user_wealth_lv")
	// //大于等于这个魅力等级的不封禁
	// maskForbidChinaUserCharmLv := s.settingRepo.GetInt("forbid_china_user_charm_lv")
	// if maskForbidChinaUserWealthLv > 0 || maskForbidChinaUserCharmLv > 0 {
	// 	//检查魅力值或者财富值
	// 	userBase, _ := s.userRepo.GetBaseCache(ctx, uid)
	// 	if userBase != nil {
	// 		if maskForbidChinaUserWealthLv > 0 && userBase.WealthLv >= maskForbidChinaUserWealthLv {
	// 			s.debugLog(fmt.Sprintf("[MaskChinaUser] 检测到用户财富值>=%d：%d-%s-%s", maskForbidChinaUserWealthLv, uid, ip, mac))
	// 			return false
	// 		}
	// 		if maskForbidChinaUserCharmLv > 0 && userBase.CharmLv >= maskForbidChinaUserCharmLv {
	// 			s.debugLog(fmt.Sprintf("[MaskChinaUser] 检测到用户魅力值>=%d：%d-%s-%s", maskForbidChinaUserCharmLv, uid, ip, mac))
	// 			return false
	// 		}
	// 	}
	// }
	// //永久封禁
	// frOpts := []repository.ForbidOpt{repository.ForbidWithRemark("大陆用户封禁"), repository.ForbidWithForever()}
	// if uid > 0 {
	// 	frOpts = append(frOpts, repository.ForbidWithUid(uid))
	// }
	// err := errs.Group{}
	// if forbidChinaUser&forbidChinaUserModeUid == forbidChinaUserModeUid {
	// 	err.Add(s.forbidRepo.BanUid(ctx, uid, math.MaxInt32, constant.ForbidRTypeOther, frOpts...))
	// }
	// if forbidChinaUser&forbidChinaUserModeIp == forbidChinaUserModeIp {
	// 	err.Add(s.forbidRepo.BanIp(ctx, ip, math.MaxInt32, constant.ForbidRTypeOther, frOpts...))
	// }
	// if forbidChinaUser&forbidChinaUserModeMac == forbidChinaUserModeMac {
	// 	err.Add(s.forbidRepo.BanMac(ctx, mac, math.MaxInt32, constant.ForbidRTypeOther, frOpts...))
	// }
	// if err.Err() != nil {
	// 	logs.Error(fmt.Sprintf("封禁国内用户操作失败：[%d-%s-%s]:%s", uid, ip, mac, err.Err()))
	// }
	return true
}

func (s *restrictionService) checkChinaUser(ctx *gin.Context) bool {
	tp, ok := ctx.Value(constant.CtxToken).(*jwt.TokenClaims)
	uid := uint64(0)
	if ok {
		uid = tp.Uid
	}
	cfCountryCode := ctx.Request.Header.Get("CF-IPCountry")
	//检查cf国家
	if cfCountryCode == "CN" {
		s.debugLog(ctx, "checkChinaUser[国家IP]: ", uid, "-", cfCountryCode)
		return true
	}
	//运营商
	simCountry := ctx.Request.Header.Get("X-SimCountry")
	if simCountry == "CN" {
		s.debugLog(ctx, "checkChinaUser[运营商国家]: ", uid, "-", simCountry)
		return true
	}
	//运营商
	simOperator := ctx.Request.Header.Get("X-SimOperator")
	if slices.Index([]string{"46000", "46002", "46007", "46001", "46003"}, simOperator) != -1 {
		s.debugLog(ctx, "checkChinaUser[运营商]: ", uid, "-", simOperator)
		return true
	}
	langs := []string{strings.ToLower(ctx.Request.Header.Get("X-Sys-Lang")), strings.ToLower(ctx.Request.Header.Get("X-Lang"))}
	strs := []string{"cn", "zh-cn", "zh", "zh_cn"}
	for i := range langs {
		for j := range strs {
			if strings.Index(langs[i], strs[j]) != -1 {
				if i == 1 {
					s.debugLog(ctx, "checkChinaUser[系统语言]: ", uid, "-", langs[i])
				} else {
					s.debugLog(ctx, "checkChinaUser[APP语言]: ", uid, "-", langs[i])
				}
				return true
			}
		}
	}
	return false
}

func (s *restrictionService) debugLog(ctx context.Context, msg any, args ...interface{}) {
	if !utils.IsProd() {
		log.WithContext(ctx).Sugar().Debugf("%s, %v", msg, args)
	}
}

// GetRestrictions 获取当前请求的限制信息
func (s *restrictionService) GetRestrictions(ctx *gin.Context) *restriction.Restrictions {
	uid := internal.GetUidFromCtx(ctx)
	ip := ctx.ClientIP()
	mac := ctx.Request.Header.Get(constant.HeaderXMac)
	rs := restriction.NewRestrictions(nil)
	if uid > 0 {
		rs.Add(s.restrictionRepo.GetRecord(ctx, restriction.TypUid, strconv.FormatUint(uid, 10)))
	}
	if mac != "" {
		rs.Add(s.restrictionRepo.GetRecord(ctx, restriction.TypMac, mac))
	}
	rs.Add(s.restrictionRepo.GetRecord(ctx, restriction.TypIp, ip))
	return rs
}
